package com.scau.controller;

import com.google.common.base.Preconditions;
import com.scau.common.annotations.CurrentUser;
import com.scau.common.annotations.resovler.CurrentUserHandlerMethodArgumentResolver;
import com.scau.common.message.ResponseMessage;
import com.scau.common.util.MessageUtil;
import com.scau.entity.Admin;
import com.scau.service.AdminService;
import com.scau.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("admins")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping(value = "register", method = RequestMethod.POST)
    public ResponseMessage<Admin> register(@RequestBody Admin admin) {

        Preconditions.checkNotNull(admin.getAccount(), "账号不能为空");
        Preconditions.checkNotNull(admin.getPassword(), "密码不能为空");

        adminService.save(admin);

        return MessageUtil.getSuccessMessage(admin);
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ResponseMessage login(@RequestBody Admin admin, HttpServletRequest request) throws Exception {

        String address = SessionUtil.getIpAddr(request);
        Preconditions.checkNotNull(admin.getAccount(), "账号不能为空");
        Preconditions.checkNotNull(admin.getPassword(), "密码不能为空");

        adminService.login(address, admin);

        return MessageUtil.getSuccessMessage();
    }

    @RequestMapping(value = "detail", method = RequestMethod.GET)
    public ResponseMessage<Admin> detail(@CurrentUser Admin admin) {
        return MessageUtil.getSuccessMessage(admin);
    }


    @RequestMapping(value = "edit", method = RequestMethod.POST)
    public ResponseMessage<Admin> edit(@CurrentUser Admin admin,@RequestBody Admin newAdmin) {

        newAdmin.setId(admin.getId());
        newAdmin = adminService.update(newAdmin);

        return MessageUtil.getSuccessMessage(newAdmin);
    }
}
